package com.csj.cloud.core.utils;

import java.util.concurrent.*;

/**
 * 自定义线程池,并可自定义拒绝策略
 **/
public class ThreadPoolDiy {
    public static void main(String[] args) {
//        ExecutorService executors = Executors.newFixedThreadPool(2);
        //核心线程数
        int corePoolSize = 3;
        //最大线程数
        int maximumPoolSize = 6;
        //超过 corePoolSize 线程数量的线程最大空闲时间
        long keepAliveTime = 2;
        //以秒为时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //创建工作队列，用于存放提交的等待执行任务
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(2);
        ThreadPoolExecutor threadPoolExecutor = null;
        try {
            //创建线程池
            threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,
                    maximumPoolSize,
                    keepAliveTime,
                    unit,
                    workQueue,
                    //采用的拒绝策略（AbortPolicy->丢弃并抛异常，CallerRunsPolicy->将被拒绝的任务添加到‘线程池正在运行的线程中去执行’，DiscardPolicy->也是丢弃任务，但是不抛出异常，DiscardOldestPolicy->丢弃队列最前面的任务，执行当前任务，如果队列里面等待了4个，那么第5个来了，丢弃他们4个）
                    new ThreadPoolExecutor.AbortPolicy());

            for (int i = 0; i < 8; i++) {
                final int index = i;
                threadPoolExecutor.submit(() -> {
                    try {
                        System.out.println("大家好，我是线程：" + index);
                        //模拟线程执行时间，10s
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
    }
}